package com.example.foods.controller;

import com.example.foods.common.Constants;
import com.example.foods.common.Utils;
import com.example.foods.domain.AjaxResult;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@Slf4j
public class PhotoController {

    @PostMapping("/upload")
    public String upload(MultipartFile file){

        String path="";

        if(file!=null && !file.isEmpty()) {
            //存放上传的文件的路径： 2024_09_12/file_id.xxx
            String subDir = Utils.generateSubDir();
            String fileId = Utils.generateUniqueFileName(file.getOriginalFilename());

            File dir = new File(Constants.UPLOAD_ROOT_DIR, subDir);
            //如果目录不存在，则创建该目录
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //创建目标文件
            File targetFile = new File(dir, fileId);
            //将上传的文件保存到指定文件中
            try {
                file.transferTo(targetFile);
                path = subDir + "/" + fileId;
            } catch (IOException e) {
                log.error("保存上传的文件时异常。" + e);
            }
        }
        return path;
    }

    @GetMapping("/deleteFile")
    public AjaxResult deleteFile(String path){
        String rootDir = Constants.UPLOAD_ROOT_DIR;
        boolean r=false;
        if(path!=null && path.length()>0) {
            File file = new File(rootDir, path);
            if(file.exists()){
                r=file.delete();
            }
        }
        return AjaxResult.ok(r);
    }
}
